﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DataEditor.Views;
using Caliburn.Micro;
using System.ComponentModel.Composition.Hosting;
using System.ComponentModel.Composition;

namespace DataEditor
{
    public class MefBootstrapper : Bootstrapper<IShell>
    {
        private CompositionContainer _container;

        protected override void Configure()
        {
            try
            {

                _container = new CompositionContainer(
                    new AggregateCatalog(AssemblySource.Instance.Select(x => new AssemblyCatalog(x)))
                    );

                var batch = new CompositionBatch();

                batch.AddExportedValue<IWindowManager>(new WindowManager());
                batch.AddExportedValue<IEventAggregator>(new EventAggregator());
                batch.AddExportedValue(_container);

                _container.Compose(batch);

                //ConventionManager.AddElementConvention<MenuItem>(ItemsControl.ItemsSourceProperty, "DataContext", "Click");
            }
            catch (Exception ex)
            {
                String message = string.Format("Boostrapper.Configure: {0}", ex.Message);
                
            }

        }

        protected override object GetInstance(Type serviceType, string key)
        {
            string contract = string.IsNullOrEmpty(key) ? AttributedModelServices.GetContractName(serviceType) : key;
            var exports = _container.GetExportedValues<object>(contract);

            if (exports.Count() > 0)
                return exports.First();

            throw new Exception(string.Format("Could not locate any instances of contract {0}.", contract));
        }

        protected override IEnumerable<object> GetAllInstances(Type serviceType)
        {
            return _container.GetExportedValues<object>(AttributedModelServices.GetContractName(serviceType));
        }

        protected override void BuildUp(object instance)
        {
            _container.SatisfyImportsOnce(instance);
        }
    }
}
